package jlfm.lastfm.client.impl.simple;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jlfm.lastfm.client.LastFmClientFaultException;
import jlfm.lastfm.playlist.LastFmRadioPlaylist;
import jlfm.lastfm.playlist.PlaylistEntry;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class PlaylistReader {
	public LastFmRadioPlaylist readPlaylist(InputStream in) {
		try {
			SAXBuilder saxBuilder = new SAXBuilder();
			Document d = saxBuilder.build(in);
			Element root = d.getRootElement();
			return parsePlaylistElement(root);
		} catch (Exception e) {
			throw new LastFmClientFaultException(e);
		}
	}

	private LastFmRadioPlaylist parsePlaylistElement(Element root) {
		LastFmRadioPlaylist pl = new LastFmRadioPlaylist();
		try {
			pl.setTitle(URLDecoder.decode(root.getChild("title").getTextTrim(),
					"UTF-8").trim());
		} catch (UnsupportedEncodingException e) {
			pl.setTitle(root.getChild("title").getTextTrim());
		}
		List<PlaylistEntry> trackList = parseTracklist(root
				.getChild("trackList"));
		pl.setTrackList(trackList);
		return pl;
	}

	private List<PlaylistEntry> parseTracklist(Element child) {
		List<PlaylistEntry> result = new ArrayList<PlaylistEntry>();
		Iterator<Element> tracks = child.getChildren("track").iterator();
		while (tracks.hasNext()) {
			Element t = tracks.next();
			PlaylistEntry pe = new PlaylistEntry();
			pe.setStreamUrl(t.getChildTextTrim("location"));
			pe.setTrack(t.getChildTextTrim("title"));
			pe.setAlbum(t.getChildTextTrim("album"));
			pe.setArtist(t.getChildTextTrim("creator"));
			pe.setTrackDuration(Integer.parseInt(t.getChildTextTrim("duration"))/1000);
			// TODO
			result.add(pe);
		}
		return result;
	}
}
